from mugenrgb import MugenRGB
from wifi import WiFi
from ntptime import settime
from machine import RTC
from machine import Timer

wifi = WiFi()
mrgb = MugenRGB(26, [[1,2,3]])


wifi.connect()
rtc = RTC()
rtc.datetime((2020, 10, 31, 0, 0, 0, 0, 8))
ntp_update_flag = True
ntp_update_timeout_count = 0
 
def ntp_update(ev):
    global ntp_update_flag
    ntp_update_flag = True

ntp_update_timer = Timer(0)
ntp_update_timer.init(period=86400000, mode=Timer.PERIODIC, callback=ntp_update)

# mrgb.fill(0x333333)
# mrgb.draw_point(4, 4, [50, 0, 0])
# mrgb.draw_rect(1, 1, 16, 5, [0, 0, 50], fill=False)
# mrgb.draw_rect(10, 3, 20, 6, [0, 30, 50], fill=True)
# mrgb.draw_line(1, 1, 16, 5, [0, 0, 50])
# mrgb.draw_line(10, 3, 20, 6, [0, 30, 50])
# mrgb.draw_text(0, 0, "Hello", mrgb.FONT7, [20, 40, 0])
# mrgb.scroll_text(0, "0123456789", mrgb.FONT7, [20, 40, 0])
# mrgb.write()

def get_datetime():
    year, month, day, weekday, hour, minute, second, microsecond = rtc.datetime()
    hour += 8
    return "%s-%s-%s %s:%s:%s" % (year, month, day, hour, minute, second)

def get_time():
    year, month, day, weekday, hour, minute, second, microsecond = rtc.datetime()
    hour += 8
    return "%2d:%2d" % (hour, minute)

current_time = get_time()
while True:
    if ntp_update_flag:
        try:
            print("Updating datetime from network")
            settime()
            ntp_update_flag = False
            ntp_update_last = get_datetime()
                
        except:
            print("Datetime update failed, attemp: %s"%ntp_update_timeout_count)
            ntp_update_timeout_count += 1
            if ntp_update_timeout_count > 10:
                ntp_update_timeout_count = 0
                print("Datetime update timeout, last update: %s"%ntp_update_last)
    
    tmp = get_time()
    if tmp != current_time:
        current_time = tmp
        print(current_time)
        mrgb.clear()
        mrgb.draw_rect(0, 0, 23, 7, [30, 10, 0])
        mrgb.draw_text(3, 2, current_time, mrgb.FONT5, [30, 30, 0])
        #mrgb.draw_text(0, 1, current_time, mrgb.FONT7, [30, 30, 30])
        mrgb.write()
